//
//  BlockController.swift
//  HHSwift
//
//  Created by 华宏 on 2019/1/22.
//  Copyright © 2019年 huahong. All rights reserved.
//

import UIKit
import RxSwift

typealias Callback = (_ value:String)->Void

class ClosuresController: BaseViewController {

    let disposeBag = DisposeBag()
    
    
    // 函数和闭包属于引用类型
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        //函数作为参数
        var arr:[Int] = []
        for _ in 0..<100 {
            arr.append(Int(arc4random()%1000))
        }
        
        //使用闭包
        arr =  arr.sorted(by:{(x:Int,y:Int) -> Bool in
            return x > y
        })
        
        //结尾闭包
        arr =  arr.sorted(by:){(x:Int,y:Int) -> Bool in
            return x > y
        }
        
        //闭包的内容捕获
        let num = 700
        arr = arr.sorted(by:{(x:Int,y:Int) -> Bool in
            return abs(x-num) > abs(y-num)
        })
        
        print("\(arr)")
        
        
    }
    

    //执行顺序：1->2->3
    func loadData(callback:(String)->()) {   //1
        callback("非逃逸闭包")                 //2
    }                                        //3
    
    
    //执行顺序：1->3->2
    func loadOtherData(callback:@escaping((String)->())) { //1
        DispatchQueue.global().async {
            DispatchQueue.main.async {
                callback("逃逸闭包")                         //2
            }
        }
    }                                                      //3
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
      
        //非逃逸闭包
        self.loadData { (data) in
            print(data)
        }
        
        
        // 逃逸闭包
        self.loadOtherData { (data) in
            print(data)
        }
    }
    
}



